package controllers

import (
	"tms-server/gin/models"

	"tms-server/utils"

	"tms-server/env"

	"net/http"

	"time"

	"fmt"
	"os"

	"io"

	"github.com/gin-gonic/gin"
)

type BasicControllers struct{}

var BasicContrl = new(BasicControllers)

func (*BasicControllers) HelloWorld(c *gin.Context) (res interface{}, e Error) {
	res = "hello world"
	return
}

type LoginResponse struct {
	UID   int64  `json:"uid"`
	Token string `json:"token"`
}

func (*BasicControllers) Login(c *gin.Context) (res interface{}, e Error) {
	uname := c.PostForm("uname")
	pwd := c.PostForm("pwd")
	platform := c.PostForm("platform")
	user, err := models.FindUserByName(uname)
	if err == env.NotFound {
		e = GenErrorMsg("用户未找到")
		return
	} else if err != nil {
		return nil, GenErrorCode(-1, err)
	}
	if utils.MD5(pwd) != user.Pwd {
		e = GenErrorMsg("密码错误")
		return
	}
	tokenExpiredAt := time.Now().Add(time.Hour)
	token, err := utils.Encrypt(UserSecert{
		UID:       user.User.Id,
		Platform:  platform,
		ExpiredAt: tokenExpiredAt,
	}, env.Confs.APPSecret)
	if err != nil {
		return nil, GenError(err)
	}
	http.SetCookie(c.Writer, &http.Cookie{
		Name:    "userId",
		Value:   string(token),
		Expires: tokenExpiredAt,
	})
	res = user.GenResponse()
	return
}

func (*BasicControllers) Upload(c *gin.Context) (res interface{}, e Error) {
	file, err := c.FormFile("attachment")
	if err != nil {
		return nil, GenError(err)
	}
	now := time.Now()
	dir := fmt.Sprintf("upload/%d%d", now.Year(), now.Month())
	if !utils.Exists(dir) {
		err = os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return nil, GenError(err)
		}
	}
	path := fmt.Sprintf("%s/%d%s", dir, now.Unix()%(3600*24*30), file.Filename)
	out, err := os.Create(path)
	if err != nil {
		return nil, GenError(err)
	}
	f, err := file.Open()
	if err != nil {
		return nil, GenError(err)
	}
	_, err = io.Copy(out, f)
	if err != nil {
		return nil, GenError(err)
	}
	attachment := models.Attachment{
		Path:     path,
		Orgpicid: 0,
		Exif:     "",
		Tm:       now,
		Orgname:  file.Filename,
	}
	err = attachment.Create()
	if err != nil {
		return nil, GenError(err)
	}
	res = map[string]interface{}{
		"id":      attachment.Id,
		"orgName": file.Filename,
	}
	return
}
